//
//  XFStatuesViewModel.m
//  SinaBlog_OC
//
//  Created by macs on 15/11/17.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

#import "XFStatuesViewModel.h"
#import "XFUserAccountModel.h"
#import "XFNetworkTools.h"
#import "SDWebImageManager.h"

@implementation XFStatuesViewModel

- (void)loadDataAndSinceId:(NSInteger)since_id
                     MaxId:(NSInteger)max_id
                  Finished:(FinishedArray)finished {

  NSString *urlString = @"2/statuses/home_timeline.json";
  NSString *token = [[XFUserAccountModel alloc] init].token;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = token;
  if (since_id != 0) {
    parameters[@"since_id"] = @(since_id);
  }
  if (max_id != 0) {
    parameters[@"max_id"] = @(max_id - 1);
  }

  [[XFNetworkTools shareNetWorkTools]
      requestJsonDictWithHttpMothod:HTTPMethodGET
                          Urlstring:urlString
                         Parameters:parameters
                        AndFinished:^(NSError *error, NSDictionary *dict) {

                          if (error != nil) {
                            //失败回调
                            finished(error, nil);
                            NSLog(@"%@", error);
                            return;
                          }

                          //创建数组接收模型数据
                          NSMutableArray *array = [NSMutableArray
                              arrayWithCapacity:[dict[@"statuses"] count]];

                          for (NSDictionary *dictonary in dict[@"statuses"]) {

                            XFStatues *statues =
                                [XFStatues statuesWithDict:dictonary];
                            [array addObject:statues];
                          }
                          [self cacheStatusImage:array and:finished];

                        }];
}

- (void)cacheStatusImage:(NSArray *)array and:(FinishedArray)finish {
  if (array.count == 0) {
    return;
  }

  dispatch_group_t group = dispatch_group_create();

  for (XFStatues *statues in array) {

    NSArray *urls = statues.danLoadPicUrl;

    if (urls.count != 1) {
      continue;
    }

    for (NSURL *imageUrl in urls) {
      dispatch_group_enter(group);
      [[SDWebImageManager sharedManager] downloadImageWithURL:imageUrl
          options:0
          progress:^(NSInteger receivedSize, NSInteger expectedSize) {

          }
          completed:^(UIImage *image, NSError *error,
                      SDImageCacheType cacheType, BOOL finished,
                      NSURL *imageURL) {

            NSLog(@"单张图片下载完成");
            dispatch_group_leave(group);
          }];
    }
  }
  //主线程完成所有图片下载回调
  dispatch_group_notify(group, dispatch_get_main_queue(), ^{

    NSLog(@"所有图片下载完成");

    finish(nil, array);
  });
}

@end
